<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getBlogComments, deleteComment } from '@/api/comment'
import { useRoute } from 'vue-router'
import { formatDateTime, formatDate } from '@/utils/date'
import { useUserStore } from '@/store/user.ts'

const { userInfo } = useUserStore()
const route = useRoute()
const id: any = ref(route.params.id || '')
const comments = ref([])
onMounted(async () => {
  const res = await getBlogComments(id.value)
  comments.value = res
  console.log(comments.value)
})

// 删除评论
const deleteCommentHandler = async (id: any) => {
  await deleteComment(id)
  // 删除成功后刷新评论列表
  const res = await getBlogComments(id)
  comments.value = res
}
</script>

<template>
  <div class="comment">
    <h2>评论列表</h2>
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <div class="comment-left">
          <div class="comment-info">
            <span class="comment-nickname">{{ comment.authorNickname }}</span>
            <span class="comment-time">{{
              formatDate(comment.createdAt)
            }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
        </div>
        <div class="comment-right">
          <el-button
            v-if="comment.authorUsername === userInfo.username"
            type="text"
            size="small"
            @click="deleteCommentHandler(comment.id)"
            >删除</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.comment-list {
  display: flex;
  flex-direction: column;
}

.comment-item {
  display: flex;
  justify-content: space-between;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  margin-bottom: 10px;
  padding: 10px;
}

.comment-left {
  flex: 1;
}

.comment-info {
  /* display: flex;
  justify-content: space-between; */
  margin-bottom: 10px;
}

.comment-nickname {
  margin-right: 15px;
  font-weight: bold;
}

.comment-time {
  color: #777;
}

.comment-right {
  display: flex;
  align-items: center;
}

.comment-content {
  word-wrap: break-word;
}
</style>
